package com.youu.youu.restapi.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youu.youu.manager.bean.Message;
import com.youu.youu.restapi.bean.ScwReturn;
import com.youu.youu.restapi.service.MessageService;

@RestController
@RequestMapping("/message")
public class MessageController {
	
	@Autowired
	MessageService messageService;
	
	
	/**
	 * 改变消息的状态
	 * @param msgid
	 * @return
	 */
	@RequestMapping("/update")
	public ScwReturn<Message> msgUpdate(Integer msgid) {
		System.out.println("改变消息的状态....");
		boolean flag = messageService.update(msgid);
		if (flag) {
			return new ScwReturn<Message>().success(null, null, null);
		}
		return new ScwReturn<Message>().fail(null, null, null);
		
	}
	
	
	/**
	 * api层的获取消息通知
	 * @return
	 */
	@RequestMapping("/list")
	public ScwReturn<Message> msgList(Integer uid, 
			@RequestParam(value="pn", defaultValue="1")Integer pn, 
			@RequestParam(value="ps", defaultValue="4")Integer ps) {
		System.out.println("api层的获取消息通知....");
		// PageHelper.startPage(pn, ps);
		ScwReturn<Message> result = new ScwReturn<>();
		try {
			// 根据用户id查出该用户的所有消息
			List<Message> msgByList = messageService.getMsgList(uid);
			// 将msgList遍历获取未读消息的数量
			int unreadCount = 0;
			for (Message message : msgByList) {
				if (message.getStatus() == 0) {
					unreadCount += 1;
				}
			}
			
			// 将消息list进行分页处理
			PageHelper.startPage(pn, ps);
			List<Message> pageMessagesList = messageService.getMsgList(uid);
			PageInfo<Message> pageInfo = new PageInfo<>(pageMessagesList);
			
			// 将处理好的结果存入返回结果对象中进行返回
			Map<String, Object> msgMap = new HashMap<>();
			msgMap.put("msgPage", pageInfo);
			msgMap.put("unreadCount", unreadCount);
			Date nowDate = new Date();
			System.out.println(nowDate);
			msgMap.put("nowDate", nowDate);
			result.setCode(1);
			result.setExt(msgMap);
		} catch (Exception e) {}
		return result;
	}
	
}
